import { Modal, Button, List, Avatar } from "antd";
import { useEffect, useState } from "react";
import { WALLET_DETECTION_RULES } from "@/utils/wallet-util";
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { useProviderHook } from "@/utils/hooks.tsx";
import { ethers } from "ethers";
import { connectWalletFailure, connectWalletStart, connectWalletSuccess, setApproveAddress } from "@/store/slices/walletSlice";
import type { RootState } from "@/store";
interface WalletInfo {
  name: string
  detected: boolean
  connectMethod: () => Promise<ethers.BrowserProvider>
}

const ConnectWallet: React.FC = () => {
  const [availableWallets, setAvailableWallets] = useState<WalletInfo[]>([]);
  const walletState = useAppSelector((state: RootState) => state.wallet);
  const dispatch = useAppDispatch();
  const { setProvider } = useProviderHook();
  useEffect(() => {
    if (!walletState.isConnected) {
      detectWallets();
    }
  }, [walletState.isConnected]);

  const detectWallets = () => {
    const wallets: WalletInfo[] = [];
    
    // 检测已安装的钱包
    Object.entries(WALLET_DETECTION_RULES).forEach(([name, walletItem]) => {
      // 跳过WalletConnect，稍后单独处理
      if (name === "WalletConnect") return;
      
      try {
        const detected = walletItem.detectFn() as boolean;
        if (detected) {
          wallets.push({
            name,
            detected,
            connectMethod: walletItem.getProvider
          });
        }
      } catch (error) {
        console.error(`检测${name}钱包时出错:`, error);
      }
    });
    
    // 始终添加walletConnect钱包
    if (WALLET_DETECTION_RULES["WalletConnect"]) {
      wallets.push({
        name: "WalletConnect",
        detected: true,
        connectMethod: WALLET_DETECTION_RULES["WalletConnect"].getProvider
      });
    }
    
    setAvailableWallets(wallets);
  };


  return (
    <Modal
      title="链接钱包"
      open={!walletState.isConnected}
      footer={null}
      closable={false}
      maskClosable={ false }
    >
      <List
        dataSource={availableWallets}
        renderItem={(wallet) => (
          <List.Item
            actions={[
              <Button 
                key="connect" 
                type="primary" 
                onClick={async () => {
                  dispatch(connectWalletStart())
                  try {
                    // 调用连接方法（可能是异步的）
                    const provider = await wallet.connectMethod()
                    
                    // 请求账户
                    let address = []
                    address = await provider.send('eth_requestAccounts', [])
                    
                    dispatch(connectWalletSuccess({ 
                      address: address[0], 
                      walletType: wallet.name 
                    }))
                    dispatch(setApproveAddress(address))
                    setProvider(provider)
                  } catch (error) {
                    console.error("钱包连接失败:", error);
                    dispatch(connectWalletFailure("钱包连接失败: " + (error as Error).message));
                  }
                }}
              >
                连接
              </Button>
            ]}
          >
            <List.Item.Meta
              avatar={<Avatar shape='square' src={`/src/assets/${wallet.name}.png`} />}
              title={wallet.name}
            />
          </List.Item>
        )}
      />
    </Modal>
  );
}

export default ConnectWallet